/*
 * File: AddWaypoint.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package triperest.servlets;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
import triperest.Destination;
import triperest.Trip;

/**
 * The Class AddWaypoint.
 */
public class AddWaypoint extends HttpServlet
{

    /*
     * (non-Javadoc)
     * 
     * @see
     * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
     * , javax.servlet.http.HttpServletResponse)
     */
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException
    {
        resp.setContentType("text/plain");
        Trip trip = new Trip(Long.valueOf(req.getParameter("trip")));
        if (req.getParameter("id") != null)
        {
            Destination waypoint = new Destination(Long.valueOf(req
                    .getParameter("id")));
            waypoint.setName(req.getParameter("waypoint"));
            trip.addDestination(waypoint);
            trip.save();
            try
            {
                JSONObject retVal = new JSONObject();
                retVal.put("waypointid", waypoint.getID());
                resp.getWriter().append(retVal.toString());
            } catch (JSONException ignore)
            {
                // Do Nothing
            }
        } else if (req.getParameter("index") != null
                && trip.getDestinations().size() > Integer.valueOf(req
                        .getParameter("index")))
        {
            Destination waypoint = trip.getDestinations().get(
                    Integer.valueOf(req.getParameter("index")));
            waypoint.setName(req.getParameter("waypoint"));
            trip.addDestination(waypoint);
            trip.save();
            try
            {
                JSONObject retVal = new JSONObject();
                retVal.put("waypointid", waypoint.getID());
                resp.getWriter().append(retVal.toString());
            } catch (JSONException ignore)
            {
                // Do Nothing
            }
        } else
        {
            Destination waypoint = new Destination();
            waypoint.setName(req.getParameter("waypoint"));
            trip.addDestination(waypoint);
            trip.save();
            try
            {
                JSONObject retVal = new JSONObject();
                retVal.put("waypointid", waypoint.getID());
                resp.getWriter().append(retVal.toString());
            } catch (JSONException ignore)
            {
                //Do Nothing
            }
        }
    }
}
